package services

import (
	"errors"
	database "hft/Database"
	"hft/Database/admin"
	"hft/global"
)

type RoomType struct{}

func (*RoomType) CreateRoom(room *admin.RoomType) (err error) {

	err = global.OC_DB.Where("name = ?", room.Name).FirstOrCreate(&room).Error

	if err != nil {
		return errors.New("该户型已存在")
	}

	return nil
}

func (*RoomType) EditRoom(room *admin.RoomType) (err error) {
	var newRoom *admin.RoomType
	if room.ID == 0 {
		return errors.New("无效的操作")
	}

	err = global.OC_DB.First(&newRoom, room.ID).Error

	if err != nil {
		return errors.New("没有该户型信息")
	}

	err = global.OC_DB.Where("id = ?", room.ID).Updates(&admin.RoomType{Name: room.Name, Base: database.Base{Sort: room.Sort}, Code: room.Code, InShow: room.InShow}).Error

	if err != nil {
		return errors.New("该标签已存在")
	}

	return nil
}

func (*RoomType) GetRoomList() (list []*admin.RoomType, err error) {

	var rooms []*admin.RoomType

	err = global.OC_DB.Order("sort desc").Find(&rooms).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	return rooms, nil
}

func (*RoomType) DeleteType(ids []int) (err error) {

	var list []*admin.RoomType

	global.OC_DB.Find(&list, ids)

	global.OC_DB.Model(&admin.RoomType{}).Unscoped().Delete(&list)

	return nil

}

var RoomServices = new(RoomType)
